package com.aqielife.demo.webflux.handler;

import com.aqielife.demo.webflux.entity.Quote;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author aqie
 * @date 2022/02/05 22:46
 * @desc
 */
@Slf4j
@Component
public class QuoteHandler {
  private final Flux<Quote> quoteStream;

  public QuoteHandler(QuoteGenerator quoteGenerator) {
    this.quoteStream = quoteGenerator.fetchQuoteStream(Duration.ofMillis(1000 * 10)).share();

  }

  public Mono<ServerResponse> hello(ServerRequest request) {
    Long start = System.currentTimeMillis();
    return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
    .body(BodyInserters.fromObject("Hello Spring!" + start));

  }

  public Mono<ServerResponse> echo(ServerRequest request) {

    return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
    .body(request.bodyToMono(String.class), String.class);

  }

  public Mono<ServerResponse> streamQuotes(ServerRequest request) {

    Long start = System.currentTimeMillis();
    log.info("--------------" + start + "--------------");
    return ServerResponse.ok()
    .contentType(MediaType.APPLICATION_STREAM_JSON) //返回多次
    .body(this.quoteStream, Quote.class);

  }

  public Mono<ServerResponse> fetchQuotes(ServerRequest request) {
    int size = Integer.parseInt(request.queryParam("size").orElse("10"));
    return ServerResponse.ok()
    .contentType(MediaType.APPLICATION_JSON)         //返回一次
    .body(this.quoteStream.take(size), Quote.class);

  }
}
